import json
import sys
import random
import threading
import time
from decimal import Decimal, ROUND_HALF_UP
from traceback import print_exc

import easygui
from tkinter import ttk

from ttzScrapyProject.constants import ColumnConstant
from ttzScrapyProject.dao.BuyModelDao import ModelDao
from ttzScrapyProject.dao.ChargeCardDao import ChargeDao
from ttzScrapyProject.dao.ExchangeCardDao import ExchangeDao
from ttzScrapyProject.dao.LotteryInfoDao import LotteryDao
from ttzScrapyProject.dao.LotteryInfoHistoryDao import HistoryDao
from ttzScrapyProject.dao.RedisBaseDao import RedisUti
from ttzScrapyProject.dao.ViewCardInfoDao import ViewCardInfo
from ttzScrapyProject.utils import MumberUtils, ModelUtils, StrigUtils
from ttzScrapyProject.utils import DateUtils
from ttzScrapyProject.utils import FileUtils
from ttzScrapyProject.utils import TkinterUtils
from ttzScrapyProject.dao import AccountLoginDao
from ttzScrapyProject.dao.UserInfoDao import UserDao
import tkinter as tk
import os
import asyncio
# # 创建一个 Lock 对象
import re
from ttzScrapyProject.utils.DateUtils import getHour, getDate, getDay
from ttzScrapyProject.utils.StrigUtils import getNoticeText
from ttzScrapyProject.utils.WeChatUtils import getStartText, send_message, getStopText
from ttzScrapyProject.vo.LoginUserVo import UserVo

# loginUserVo = UserVo()
lock = threading.Lock()


async def exchangeCardFlow(loginUserVo,redis,name):
    try:
        print(f"Executing task: {name}")
        # 为了适配换卡流程,loginUserVo 重新从redis获取
        loginUserVo = redis.getStartInfo(loginUserVo.phone)
        if not loginUserVo.exchangeIsCard:
            print(f"{loginUserVo.phone}设置为不交换卡片,跳过换卡片流程")
            return
        exchangeCardFlowKey= f"{loginUserVo.phone}-exchangeCardFlow"

        if not redis.getexchangeCardFlow(exchangeCardFlowKey):
            send_message(loginUserVo.userNoticeList,f"{loginUserVo.phone}开始换卡流程")
            userToken = redis.getUserToken(loginUserVo.phone)
            num = ExchangeDao().getExchangeNum(userToken)
            time.sleep(random.randint(1, 3))
            if num !=0:
                for i in range(1):
                    time.sleep(random.randint(1, 3))
                    ExchangeDao().compose(userToken,loginUserVo)
                redis.setExchangeCardFlow(exchangeCardFlowKey)
            print(f"Executing finished : {name}")
        print("今日已更换过卡片,无需再次更换")
    except:
        print_exc()
        print(f"Executing failed : {name}")

"""
    账户卡密充值
"""
async def chargePhoneCard(loginUserVo,redis,name):
    try:
        print(f"Executing task: {name}")
        print(f"{loginUserVo.phone} 卡密充值开始")
        userToken = redis.getUserToken(loginUserVo.phone)
        ChargeDao().chargeUser(loginUserVo,userToken)
        print(f"Executing finished : {name}")
    except:
        print(f"{loginUserVo.phone} 账号充值失败")
        print(f"Executing failed : {name}")

async def readCardInfo(loginUserVo,redis,name):
    try:
        print(f"Executing task: {name}")
        userToken = redis.getUserToken(loginUserVo.phone)
        ViewCardInfo().getCardInfo(loginUserVo,userToken)
        print(f"Executing finished : {name}")
    except:
        print_exc()
        print(f"{loginUserVo.phone} 卡密信息获取异常")
        print(f"Executing failed : {name}")


def updateTimeLabel(loop, comboboxCost_var, comboboxModel_var, comboboxSnowball_var, comboboxSnowballtarget_var,
                    comboboxWin_var, loginUserVo, redis, indexWindow, time_label, surplus_time_label,
                    model_label, win_label, userIdText_label, yinzhuText_label,
                    treeview, randomSecond=None):
    # i = getCountDown()
    try:
        taskList = []
        second = DateUtils.getSecondDistince(90)
        # hour12Second = DateUtils.getSecondDistince12Hour()
        if randomSecond is None:
            randomSecond = random.randint(45,55)
        print(f"将在 {randomSecond}秒开始下注")
        if second < randomSecond+1 and second > randomSecond-1:
            # 创建事件循环
            randomSecond = random.randint(45,55)
            # loop = asyncio.get_event_loop()
            taskList.append(start_scrapyModel(comboboxCost_var, comboboxModel_var, comboboxSnowball_var, comboboxSnowballtarget_var,
                                              comboboxWin_var,loginUserVo, model_label, win_label,userIdText_label,yinzhuText_label,treeview,redis,indexWindow,"买入流程"))
            taskList.append(update_treeview(treeview, indexWindow,"更新数据流程"))
            taskList.append(exchangeCardFlow(loginUserVo,redis,"更换卡片流程"))
            taskList.append(chargePhoneCard(loginUserVo,redis,"账号充值流程"))
        # 每3天提取一下卡密
        if DateUtils.getSecondDistince(1*60*60*24*3)<10:
            taskList.append(readCardInfo(loginUserVo,redis,"卡密信息获取流程"))
            # 并发执行任务
        if len(taskList)!=0:
            loop.run_until_complete(asyncio.gather(*taskList))

        surplus_time_label.config(text=f"当前剩余{second}秒")
        time_label.config(text=DateUtils.getDate())
        indexWindow.after(1000, lambda: updateTimeLabel(loop,comboboxCost_var, comboboxModel_var, comboboxSnowball_var, comboboxSnowballtarget_var,
                                                        comboboxWin_var, loginUserVo,redis,indexWindow,time_label, surplus_time_label,
                                                        model_label, win_label, userIdText_label, yinzhuText_label,
                                                        treeview,randomSecond))
    except:
        loginUserVo.setCountDownFuck(20)
        print_exc()
        pass

async def update_treeview(treeview, window,name):
    try:
        print(f"Executing task: {name}")
        rows = treeview.get_children()
        row_count = len(rows)
        id_list = []
        for row in rows:
            data = treeview.item(row)
            id_list.append(str(data['values'][0]))
        if row_count > 30:
            treeview.delete(*treeview.get_children())  # 清空Treeview控件

        with open('lotterInfoItem.txt', 'r', encoding="utf-8") as file:
            for line in file:
                values = line.strip().split(',')
                valuesList = list(values)
                # for index, item in enumerate(my_list):
                #     print(index, item)
                temp = []
                tempStr = ""
                for index, item in enumerate(valuesList):
                    if item is not None:
                        if index == 1 or index == 2:
                            tempStr = tempStr + item + "+"
                        elif index == 3:
                            tempStr = tempStr + item + "="
                        elif index == 4:
                            tempStr = tempStr + item
                        elif index == 5:
                            temp.append(tempStr)
                        else:
                            temp.append(item)
                    else:
                        temp.append("None")

                if temp[0] not in id_list:
                    treeview.insert("", 1, values=tuple(temp))
        print(f"Task {name} finished")
    except:
        print(f"Task {name} failed")
        print(f"lotterInfoItem.txt 不存在")



"""
userData 用户手机号,用户密码
"""


def start_scrapy(loginUserVo, window):
    # 获取首页数据
    loginUserVo = LotteryDao().getIndexLotteryInfo(loginUserVo)
    # print(f"目录是{dir}")
    # os.chdir(dir)
    # print(f"目录是{os.chdir(dir)}")
    # command = f'scrapy crawl tantanshu -a userToken={userToken}'
    # # command = f'scrapy crawl tantanshu -a userToken={userToken} -a userData={userData}'
    # os.system(command)
    if loginUserVo.isScrpay:
        window.after(1000 * 60 * 30, lambda: start_scrapy(loginUserVo, window))
    else:
        pass
        # window.after(1000 * 60 * 1, lambda: start_scrapy(loginUserVo, window))


def checkIsStartAndPushWeChatMessage(loginUserVo,redis):
    if MumberUtils.strToInt(loginUserVo.startHour) <= MumberUtils.strToInt(getHour())\
            and MumberUtils.strToInt(getHour())<=MumberUtils.strToInt(loginUserVo.endHour) and loginUserVo.todayIsStart:
        print(f"命中了时间段,开启下注")
        redisStartKey = getNoticeText(loginUserVo,getDay(),"startNotice")
        dateStr = getDate()
        startStr = getNoticeText(loginUserVo,dateStr,"startNotice")
        loginUserVo = UserDao().getUserInfo(loginUserVo)
        if not redis.exists(redisStartKey):

            startText = getStartText(loginUserVo.phone,loginUserVo.coinBean,loginUserVo.snowballtarget,loginUserVo.winAmount,dateStr,loginUserVo.model)
            flag = send_message(loginUserVo.userNoticeList,startText)
            if flag:
                redis.setStartText(redisStartKey)

        return True
    else:
        print(f"不满足下注时间段,请稍后再试,{loginUserVo.startHour}~{loginUserVo.endHour}时间段开启")
        return False
        # randNum = random.randint(0,2) * 60

        # time.sleep(randNum)
        # print("延迟完毕了")



async def start_scrapyModel(comboboxCost_var, comboboxModel_var, comboboxSnowball_var, comboboxSnowballtarget_var,
                            comboboxWin_var,loginUserVo, model_label, win_label,userIdText_label,yinzhuText_label,treeview,redis,indexWindow,name):
    try:
        # 读取redis 信息
        print(f"Executing task: {name}")
        loginUserVo = redis.getStartInfo(combobox_selected(comboboxPhone_var))
        setIndexWindowData(comboboxCost_var, comboboxModel_var, comboboxSnowball_var, comboboxSnowballtarget_var,
                           comboboxWin_var, loginUserVo)
        # 校验token 如果token 在缓存中不存在，则
        # 1.退出登录
        # 2.重新登录
        loginUserVo.usertoken = checkUserTokenLegal(loginUserVo, loginUserVo.phone, redis)
        if not checkIsStartAndPushWeChatMessage(loginUserVo,redis) :
            return

        doingData = LotteryDao().getIndexLotteryInfo(loginUserVo)
        print(f"当前正在进行的抽奖次数是{len(doingData)}")
        if len(doingData)<5:
            print(f"当前正在进行的抽奖小于5次")
            return


        loginUserVo = LotteryDao().getDoingLotteryInfo(loginUserVo)
        # 获取下注历史信息数据
        loginUserVo = HistoryDao().getHistoryData(loginUserVo,redis)
        if not loginUserVo.stop:
            # 微信通知start
            redisEndKey =  getNoticeText(loginUserVo,getDay(),"endNotice")
            dateStr = getDate()
            # endStr = getNoticeText(loginUserVo,dateStr,"endNotice")
            if not redis.exists(redisEndKey):
                endText =getStopText(loginUserVo.phone,loginUserVo.coinBean,dateStr,loginUserVo.model)
                # send_message(toUser,startText)

                flag = send_message(loginUserVo.userNoticeList,endText)
                if flag:
                    redis.setStartText(redisEndKey)
            ############# ==========================微信通知end
        # 获取历史下注数据
        if loginUserVo.stop:
            if StrigUtils.notConstrainModel(loginUserVo):
                loginUserVo = ModelDao().buy(loginUserVo)
                loginUserVo = UserDao().getUserInfo(loginUserVo)

        userIdText_label.config(text=loginUserVo.phone)
        yinzhuText_label.config(text=loginUserVo.coinBean)
        model_label.config(text=f"当前波数{loginUserVo.currentSnowballParentIndex},第{loginUserVo.currentSnowballChildrenIndex}轮" )
        # loginUserVo = setCommonStartLoginUserVoData(loginUserVo, model_label, redis)
        # 避免重复下注
        # commonStartApplication(loop,loginUserVo,redis,indexWindow,False,labelUserId,labelCobin,model_label,treeview)
        win_label.config(text=f"当前今日盈亏{loginUserVo.TodayWin}")
        print(f"Task {name} finished")
    except:
        print_exc()
        print(f"请求底层接口失败,更新标签信息失败")
        print(f"Task {name} failed")
    finally:
        pass



def setCommonStartLoginUserVoData(loginUserVo, model_label, redis):
    usertoken = loginUserVo.usertoken
    tempCoinBean = loginUserVo.coinBean
    currentSnowballParentIndex = loginUserVo.currentSnowballParentIndex
    currentSnowballChildrenIndex = loginUserVo.currentSnowballChildrenIndex
    model_label.config(
        # text=f"当前方案第{loginUserVo.currentSnowballParentIndex + 1}轮,第{loginUserVo.currentSnowballChildrenIndex + 1}波")
        text=f"当前方案第{loginUserVo.currentSnowballParentIndex}轮,第{loginUserVo.currentSnowballChildrenIndex}波")
    loginUserVo = redis.getStartInfo(combobox_selected(comboboxPhone_var))
    loginUserVo.usertoken = usertoken
    loginUserVo.currentSnowballChildrenIndex = currentSnowballChildrenIndex
    loginUserVo.currentSnowballParentIndex = currentSnowballParentIndex
    divisor = 100000
    result = Decimal(convertAmount(loginUserVo.snowballtarget)) / Decimal(divisor)
    result = result.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)  # 保留两位小数，四舍五入
    # modelList = getXZModelData("14N","14-0",1)
    if loginUserVo.model.find("N")!= -1:
        modelData = ModelUtils.getXZModelData(loginUserVo.model[0:2], loginUserVo.model, result)[
                    :MumberUtils.strToInt(loginUserVo.snowballCount) + 1]
    else:
        #如果没有匹配到则说明是组合
        firstResult = re.sub(r'\-\d{1,}', 'N', loginUserVo.model)
        modelData = ModelUtils.getXZModelData(firstResult, loginUserVo.model, result)[
                    :MumberUtils.strToInt(loginUserVo.snowballCount) + 1]
    loginUserVo.setModelData(modelData)
    loginUserVo.coinBean = tempCoinBean
    return loginUserVo


def convertAmount(amount):
    if amount == "":
        return 999999999999999
    else:
        if amount.find("w")!= -1:
            amount = amount.replace("w", "")
            amount = MumberUtils.strToInt(amount) * 10000
            return amount
        return amount


def startApplication(loop,comboboxCost_var, comboboxModel_var, comboboxSnowball_var, comboboxSnowballtarget_var,
                     comboboxWin_var, loginUserVo,redis,indexWindow,time_label, surplus_time_label,
                     model_label, win_label, userIdText_label, yinzhuText_label,
                     treeview):
    randomSecond = random.randint(45,55)
    # try:
    indexWindow.after(1000, lambda: updateTimeLabel(loop,comboboxCost_var, comboboxModel_var, comboboxSnowball_var, comboboxSnowballtarget_var,
                                                    comboboxWin_var, loginUserVo,redis,indexWindow,time_label, surplus_time_label,
                                                    model_label, win_label, userIdText_label, yinzhuText_label,
                                                    treeview,randomSecond))
    # finally:
    #     pass
    indexWindow.mainloop()



def combobox_selected(combobox_var):  # 下拉框选择时触发
    return combobox_var.get()  # 获取值


def submit_form(comboboxPhone_var):
    redis = RedisUti()
    # 获取用户选择的手机号
    phone = combobox_selected(comboboxPhone_var)
    # 初始化密码为qm1006406 默认密码

    loginUserVo = redis.getStartInfo(combobox_selected(comboboxPhone_var))

    loginUserVo.usertoken = checkUserTokenLegal(loginUserVo, phone, redis)

    # 用户token
    userToken = loginUserVo.usertoken
    # 打印用户输入的内容
    if userToken is not None and len(userToken) == 0:
        easygui.msgbox("登录失败,请重新登录,若重复失败,请联系开发18340057070", "消息框")
        sys.exit()
        loginWindow.destroy()
    userToken_label.config(text=userToken)
    print(f"userToken的值为{TkinterUtils.get_label_value(userToken_label)}")

    result = easygui.buttonbox("登录成功,是否继续", choices=["是", "否"])

    try:
        if result == "是":
            loginWindow.destroy()
            # 获取用户信息
            redis.setCurrentSnowballParentIndex(phone,0)
            redis.setCurrentSnowballChildrenIndex(phone,0)
            loginUserVo = UserDao().getUserInfo(loginUserVo)
            commonStartApplication(loginUserVo,redis)
        else:
            sys.exit()
            loginWindow.destroy()
    except:
        print_exc()


def checkUserTokenLegal(loginUserVo, phone, redis):
    try:
        password = "qm1006406"
        print(f"=========本次登录的手机号{phone},密码{password}")
        # 如果从未登录过,则进行登录
        loginUserVo.usertoken = redis.getUserToken(phone)
        if len(loginUserVo.usertoken) == 0:
            data = {
                "Cellphone": phone,
                "Password": password
            }
            loginUserVo = AccountLoginDao.accountLogin(data, loginUserVo)
            redis.setUserToken(phone, loginUserVo.usertoken)
            userToken = loginUserVo.usertoken
        # 如果用户token剩余1000 ms过期,先退出,再重新登录
        elif redis.getTTL(phone) >= 0 and redis.getTTL(phone) < 1000:
            print(f"=========本次登录的手机号{phone},密码{password}，已过期")
            data = {
                "Cellphone": phone,
                "Password": password
            }
            # 先登出,再登录
            AccountLoginDao.accountLogout(data, loginUserVo.usertoken)
            loginUserVo = redis.getStartInfo(loginUserVo.phone)
            loginUserVo = AccountLoginDao.accountLogin(data, loginUserVo)
            redis.setUserToken(phone, loginUserVo.usertoken)
            userToken = loginUserVo.usertoken
        # 如果登录失败,则销毁窗口
        if len(loginUserVo.usertoken) == 0:
            errorText = f"预警:{phone}-用户登录失败,请联系管理员"
            print(errorText)
            send_message(loginUserVo.userNoticeList,errorText)
            return ""
        print(f"userToken的值为{loginUserVo.usertoken}")
        return loginUserVo.usertoken
    except:
        print_exc()
        send_message(loginUserVo.userNoticeList,f"{phone}用户登出登录接口请求失败了,请联系管理员")


def commonStartApplication(loginUserVo,redis):
    # 副窗口
    indexWindow = tk.Tk()
    # 指定窗口大小
    # window.geometry('400x200')
    userId_label = tk.Label(indexWindow, text="用户id:")
    userId_label.grid(row=0, column=0)
    userIdText_label = tk.Label(indexWindow, text="测试用户")
    userIdText_label.grid(row=0, column=1)
    # 银珠数量 ,定时任务更新
    yinzhu_label = tk.Label(indexWindow, text="银珠数量")
    yinzhu_label.grid(row=1, column=0)

    yinzhuText_label = tk.Label(indexWindow, text="0")
    yinzhuText_label.grid(row=1, column=1)
    # 模式选择
    model_labeltext = tk.Label(indexWindow, text="模式选择")
    model_labeltext.grid(row=3, column=0)
    # 模式下拉框取值
    modelValues = ["2N0", "2N1", "3N0", "3N1", "3N2", "4N0", "4N1", "4N2", "4N3", "5N0", "5N1", "5N2", "5N3", "5N4"]
    comboboxModel_var = tk.StringVar()
    combobox = ttk.Combobox(indexWindow, values=modelValues, width=10, textvariable=comboboxModel_var)
    combobox.grid(row=3, column=1)
    # 盈利目标和盈利目标共用
    tempValues = ["", "1w", "5w", "10w", "50w", "100w", "200w", "300w", "400w", "500w", "600w", "700w", "800w",
                  "900w",
                  "100w", "1100w", "1200w", "1300w", "1400w", "1500w", "1600w", "1700w", "1800w", "4000w", "5000w",
                  "6000w", "7000w", "8000w", "9000w", "10000w"]
    # 盈利目标标签
    win_label = tk.Label(indexWindow, text="盈利目标")
    win_label.grid(row=4, column=0)
    # 盈利目标设置
    winValues = tempValues
    comboboxWin_var = tk.StringVar()
    combobox = ttk.Combobox(indexWindow, values=winValues, width=10, textvariable=comboboxWin_var)
    combobox.grid(row=4, column=1)
    # 亏损目标标签
    cost_label = tk.Label(indexWindow, text="亏损目标")
    cost_label.grid(row=5, column=0)
    # 亏损目标设置
    costValues = tempValues
    comboboxCost_var = tk.StringVar()
    combobox = ttk.Combobox(indexWindow, values=costValues, width=10, textvariable=comboboxCost_var)
    combobox.grid(row=5, column=1)
    # 滚雪球轮数设置
    Snowball_label = tk.Label(indexWindow, text="雪球模式设置")
    Snowball_label.grid(row=6, column=0)
    # 雪球模式轮数下拉框取值
    SnowballValues = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17",
                      "18",
                      "19", "20", "21", "22", "23"]
    comboboxSnowball_var = tk.StringVar()
    combobox = ttk.Combobox(indexWindow, values=SnowballValues, width=10, textvariable=comboboxSnowball_var)
    combobox.grid(row=6, column=1)
    # 滚雪球每期目标设置
    snowball_label = tk.Label(indexWindow, text="每期目标")
    snowball_label.grid(row=7, column=0)
    values = ["0.5w", "1w", "2w", "5w", "10w", "20w", "30w", "40w", "50w", "60w", "70w", "80w", "90w", "100w",
              "110w",
              "120w", "130w",
              "140w", "150w", "160w", "170w", "180w", "190w", "200w", "210w", "220w", "230w", "240w",
              "250w", "260w", "270w", "280w",
              "290w", "300w", "310w"
              ]
    comboboxSnowballtarget_var = tk.StringVar()
    combobox = ttk.Combobox(indexWindow, values=values, width=10, textvariable=comboboxSnowballtarget_var)
    combobox.grid(row=7, column=1)
    # 北京时间
    time_label = tk.Label(indexWindow, text="时间显示在这里")
    time_label.grid(row=3, column=3)
    # 剩余下注时间
    surplus_time_label = tk.Label(indexWindow, text="剩余下注时间")
    surplus_time_label2 = tk.Label(indexWindow, text="")
    surplus_time_label.grid(row=4, column=3)
    surplus_time_label2.grid(row=4, column=4)

    # 下注方案显示
    model_label = tk.Label(indexWindow, text="下注方案显示在这里")
    model_label.grid(row=5, column=3)
    # 盈利目标显示
    win_label = tk.Label(indexWindow, text="盈利目标")
    win_label.grid(row=6, column=3)
    # 创建Treeview 控件 ,Execl表格组件

    treeview = ttk.Treeview(indexWindow)
    treeview["columns"] = ("期号", "号码", "奖池", "下注时间", "下注金额", "是否下注", "中奖金额")
    # 设置列的标题
    treeview.heading("期号", text="期号")
    treeview.heading("号码", text="号码")
    treeview.heading("奖池", text="奖池")
    treeview.heading("下注时间", text="下注时间")
    treeview.heading("下注金额", text="下注金额")
    treeview.heading("是否下注", text="是否下注")
    treeview.heading("中奖金额", text="中奖金额")
    # 显示表格
    treeview.grid(row=25, columnspan=10)
    # # 创建事件循环
    loop = asyncio.get_event_loop()
    current_dir = os.getcwd()
    # 启动应用按钮
    # startApplicationButton = tk.Button(indexWindow, text="启动应用",
    #                                    command=lambda: )
    # startApplicationButton.grid(row=7, column=3)
    startApplication(loop,comboboxCost_var, comboboxModel_var, comboboxSnowball_var, comboboxSnowballtarget_var,
                     comboboxWin_var, loginUserVo,redis,indexWindow,time_label, surplus_time_label,
                     model_label, win_label, userIdText_label, yinzhuText_label,
                     treeview)




def setIndexWindowData(comboboxCost_var, comboboxModel_var, comboboxSnowball_var, comboboxSnowballtarget_var,
                       comboboxWin_var, loginUserVo):
    comboboxCost_var.set(loginUserVo.costAmount)
    comboboxWin_var.set(loginUserVo.winAmount)
    comboboxSnowball_var.set(loginUserVo.snowballCount)
    comboboxSnowballtarget_var.set(loginUserVo.snowballtarget)
    comboboxModel_var.set(loginUserVo.model)
    # 模式选择
    model = combobox_selected(comboboxModel_var)
    # 盈利目标
    win = combobox_selected(comboboxWin_var)
    # 亏损目标
    cost = combobox_selected(comboboxCost_var)
    # 雪球模式轮数获取
    snowballCount = combobox_selected(comboboxSnowball_var)
    # 雪球模式目标获取
    snowballtarget = combobox_selected(comboboxSnowballtarget_var)
    winAmount = convertAmount(win)
    costAmount = convertAmount(cost)
    snowballtarget1 = convertAmount(snowballtarget)
    loginUserVo.setModel(model)
    loginUserVo.setWinAmount(winAmount)
    loginUserVo.setCostAmount(costAmount)
    loginUserVo.setSnowballCount(snowballCount)
    loginUserVo.setSnowballtarget(snowballtarget1)
    divisor = 100000
    result = Decimal(loginUserVo.snowballtarget) / Decimal(divisor)
    result = result.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)  # 保留两位小数，四舍五入
    # 下注
    # modelList = getXZModelData("14N","14-0",1)
    if loginUserVo.model.find("N")!= -1:
        modelData = ModelUtils.getXZModelData(loginUserVo.model[0:2], loginUserVo.model, result)[
                    :MumberUtils.strToInt(loginUserVo.snowballCount) + 1]
    else:
        #如果没有匹配到则说明是组合
        firstResult = re.sub(r'\-\d{1,}', 'N', loginUserVo.model)
        modelData = ModelUtils.getXZModelData(firstResult, loginUserVo.model, result)[
                    :MumberUtils.strToInt(loginUserVo.snowballCount) + 1]
    loginUserVo.setModelData(modelData)
    # 滚雪球的次数
    loginUserVo.setModelSnowballCount(len(loginUserVo.modelData))
    for i in loginUserVo.modelData:
        # 滚雪球的轮数
        loginUserVo.setLuckCount(len(i))
        break
        data = FileUtils.readUserLoginContext("userLoginInfo.txt")
    # phone = data["phone"]
    # password = data["password"]
    # 爬虫应用身份标识 True 为爬虫, False 为下注版本
    # 初始化滚雪球数据
    # item = {
    #     "currentSnowballParentIndex": loginUserVo.currentSnowballParentIndex,
    #     "currentSnowballChildrenIndex": loginUserVo.currentSnowballChildrenIndex
    # }
    # FileUtils.writeSnowballData("SnowballData.txt", item)


if __name__ == '__main__':
    loginWindow = tk.Tk()
    # 创建姓名标签和输入框
    loginWindow.geometry("300x200")
    # 手机号下拉框
    dao = UserDao()
    # 获取所有的手机号
    phoneValues = dao.getAllUser()
    comboboxPhone_var = tk.StringVar()
    combobox = ttk.Combobox(loginWindow, values=phoneValues, width=20, textvariable=comboboxPhone_var)
    combobox.grid(row=1, column=1)
    name_label = tk.Label(loginWindow, text="手机号:")
    name_label.grid(row=1, column=0)

    userToken_label = tk.Label(loginWindow, text="userToken的值将显示在这里")
    userToken_label.grid(row=4, columnspan=2)
    # 创建提交按钮
    submit_button = tk.Button(loginWindow, text="账号登录", command=lambda: submit_form(comboboxPhone_var))
    submit_button.grid(row=3, columnspan=2)
    loginWindow.mainloop()
"""
#执行一次：
#2019年3月1日0时0分0秒执行该程序
sched.add_job(job_fun, 'cron', year=2019,month = 03,day = 1,hour = 0,minute = 0,second = 0)
#从星期一到星期五5:30（AM）直到2014-05-30 00:00:00
sched.add_job(job_fun, 'cron', day_of_week='mon-fri', hour=5, minute=30,end_date='2014-05-30'
 
#间隔多长时间后执行
#每隔30分钟执行一次
sched.add_job(my_job, 'interval',minutes = 30)
#每隔2天10时20分30秒执行一次任务
sched.add_job(my_job, 'interval',days  = 2,hours = 10,minutes = 20,seconds = 30)
#注意：执行一次时是day，间隔执行时为days，注意参数后面是否加's'
"""
